package com.aiit.controller;
import com.aiit.pojo.Patient;
import com.aiit.pojo.ProcResult;
import com.aiit.pojo.User;
import com.aiit.service.impl.UserService;
import com.aiit.utils.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * ClassName:UserController
 * Package:com.aiit.controller
 * Description:
 *
 * @Date:2020/4/10 14:25
 * @Author:xjs
 */
@Slf4j
@Controller
public class UserController {
    @Resource
    private UserService userService;

    @GetMapping("/login")
    public String login(){
        return "/login";
    }
    @GetMapping("/register")
    public String register(){
        return "/register";
    }

    @RequestMapping(value="toRegist",method=RequestMethod.POST)
    @ResponseBody
    public ProcResult toRegist(@RequestBody User user)
    {
		System.out.println("请求到达这里，toRegist用户");
        System.out.println("请求到达这里"+user);
        if (StringUtils.isNullOrEmpty(user.getUsername())) {
            return ProcResult.fail().bind("msg", "用户名不能为空");

        }
        if (StringUtils.isNullOrEmpty(user.getPassword())) {
            return ProcResult.fail().bind("msg", "密码不能为空");

        }
       if(userService.userRegist(user)>0) {
            return ProcResult.success().bind("msg", "注册成功");
        }
        return ProcResult.fail();

    }
    @RequestMapping(value="toUserName",method=RequestMethod.POST)
    @ResponseBody
    public ProcResult checkName(@RequestParam("username")String username)
    {
        System.out.println("请求到达这里，toUserName用户"+username);
       if(userService.selectUserName(username)!=null){
           return ProcResult.fail();
       }
        return ProcResult.success();
    }
    @PostMapping("/login")
    public String login(User user,Model model, HttpServletRequest request){
        HttpSession session=request.getSession();
        Subject subject = SecurityUtils.getSubject();//获取当前主体
        session.setAttribute("sessionValue",user.getUsername());
        AuthenticationToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        // 执行登录
        // 没有返回值
        subject.login(token);
        log.info("===============list>"+userService.findUserContent());
        PageHelper.startPage(1, 2);//从第几页开始查询，每次查询10条记录  ：pageNo=(当前页数-1)*10
        List<User> list = userService.findUserContent();//startPage后紧跟的这个查询就是分页查询
        //使用PageInfo包装查询结果，只需要将pageInfo交给页面就可以
        PageInfo<User> pageInfo = new PageInfo<User>(list,5);

        model.addAttribute("pageInfo", pageInfo);
        //获得当前页
        model.addAttribute("pageNum", pageInfo.getPageNum());
        //获得一页显示的条数
        model.addAttribute("pageSize", pageInfo.getPageSize());
        //是否是第一页
        model.addAttribute("isFirstPage", pageInfo.isIsFirstPage());
        //获得总页数
        model.addAttribute("totalPages", pageInfo.getPages());
        //是否是最后一页
        model.addAttribute("isLastPage", pageInfo.isIsLastPage());
        User user2=userService.selectUserName(user.getUsername());
        System.out.println(user2);
        int roleId=userService.userRoleId(user2.getUserid());
        System.out.println(roleId);
        if(roleId==2){
            return "redirect:/doctor/patients";
        }
          return "redirect:/index";
    }
    @RequestMapping("/index")
    public String index(HttpServletRequest request,Model model, @RequestParam(defaultValue="1") int pageNum, @RequestParam(defaultValue="2") int pageSize,
                        @RequestParam(defaultValue="") String action, @RequestParam(defaultValue="") String keyword){
        List<User> list = null;
        System.out.println(" keyword:"+action+" keyword:"+keyword);
        log.info("===============list>"+userService.findUserContent());
        //引入分页查询，使用PageHelper分页功能在查询之前传入当前页，然后多少记录
        PageHelper.startPage(pageNum, pageSize);//从第几页开始查询，每次查询10条记录  ：pageNo=(当前页数-1)*10
        if(action==null||action.equals("")){
            list = userService.findUserContent();
            log.info("===============findUserContent>"+ list);
        }else{
            //list = userService.findUserContent();//startPage后紧跟的这个查询就是分页查询
            list=userService.search(action,keyword);
            log.info("===============keyword>"+keyword+":"+ list);
        }

        //使用PageInfo包装查询结果，只需要将pageInfo交给页面就可以
        PageInfo<User> pageInfo = new PageInfo<User>(list,5);

        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("action",action);
        model.addAttribute("keyword",keyword);
        //获得当前页
        model.addAttribute("pageNum", pageInfo.getPageNum());
        //获得一页显示的条数
        model.addAttribute("pageSize", pageInfo.getPageSize());
        //是否是第一页
        model.addAttribute("isFirstPage", pageInfo.isIsFirstPage());
        //获得总页数
        model.addAttribute("totalPages", pageInfo.getPages());
        //是否是最后一页
        model.addAttribute("isLastPage", pageInfo.isIsLastPage());
            return "index";
    }
    @PostMapping("/findById")
    @ResponseBody
    public ProcResult findById(@RequestParam("userid") int userid){

        List<User> list=userService.findById(userid);

        return ProcResult.success().bind("list", list);
    }

    @RequestMapping(value = "/excel/OutputExcel", produces = "application/form-data; charset=utf-8")
    @ResponseBody
    public String OutputExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("导出");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html,charset=utf-8");

        List<Patient> list = userService.doctorFindPatients();

        String message = ExcelUtil.OutExcel(request, response, list);
        if (message.equals("fail")) {
            ServletOutputStream out = response.getOutputStream();
            message = "导出失败，请重试";
            String s = "<!DOCTYPE HTML><html><head><script>alert('" + message + "');</script></head><body></body></html>";
            out.print(s);
        }
        return null;
    }
 /*   @GetMapping("/unautho")
    @ResponseBody
    public String unautho() {
        return "未授权的页面！请联系管理员！2964524368@qq.com";
    }*/
}
